//
//  AppDelegate.m
//  GuardMan
//
//  Created by steven on 2017/2/23.
//  Copyright © 2017年 steven. All rights reserved.
//

#import "AppDelegate.h"
#import "GMLoginViewController.h"
#import "GMNavigationController.h"

#import <MMDrawerController/MMDrawerController.h>
#import <MMDrawerController/UIViewController+MMDrawerController.h>
#import "GMMenuViewController.h"
#import "GMDebtorListViewController.h"
#import "GMCarViewController.h"
#import "GMGuardListViewController.h"
#import "GMSubUserViewController.h"
#import "GMLoginDataController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <AMapFoundationKit/AMapServices.h>

@interface AppDelegate ()

@property (nonatomic, strong)MMDrawerController *drawerController;
@property (nonatomic, strong)GMLoginDataController *loginDataController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [UIViewController new];

    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if (token) {
        self.loginDataController = [[GMLoginDataController alloc] init];
        __weak typeof(self)weakSelf = self;
        [self.loginDataController getUserWithCallback:^(NSString *error) {
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (error == nil) {
                NSDictionary *userDict = self.loginDataController.userDictionary;
                NSString *userId = [userDict[@"id"] stringValue];
                NSString *name = userDict[@"name"];
                NSString *headImg = userDict[@"headImg"];
                NSString *type = userDict[@"type"];
                NSString *vip = userDict[@"vip"];
                NSString *mobile = userDict[@"account"];
                NSString *recommend = userDict[@"recommend"];

                NSLog(@"Login succeed\nid:%@\nname:%@\nToken:%@", userId, name, token);

                // store user info
                [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"name"];
                [[NSUserDefaults standardUserDefaults] setObject:headImg forKey:@"headImageUrl"];
                [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
                [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"type"];
                [[NSUserDefaults standardUserDefaults] setObject:vip forKey:@"vip"];
                [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"mobile"];
                [[NSUserDefaults standardUserDefaults] setObject:recommend forKey:@"recommend"];
                [[NSUserDefaults standardUserDefaults] synchronize];

                dispatch_async(dispatch_get_main_queue(), ^{
                    // Login success
                    [strongSelf setupMainViewController];
                });
            } else {
                GMLoginViewController *loginViewController = [[GMLoginViewController alloc] init];
                GMNavigationController *navigationController = [[GMNavigationController alloc] initWithRootViewController:loginViewController];
                self.window.rootViewController = navigationController;

                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"%@", error);
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登录失败" message:error preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                        NSLog(@"You pressed button OK");
                    }];
                    [alertController addAction:defaultAction];
                    [loginViewController presentViewController:alertController animated:YES completion:nil];
                });
            }
        }];

    } else {
        GMLoginViewController *loginViewController = [[GMLoginViewController alloc] init];
        GMNavigationController *navigationController = [[GMNavigationController alloc] initWithRootViewController:loginViewController];
        self.window.rootViewController = navigationController;
    }

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    [self setNavigationBarStyle];
    [self setupKeyboardManager];
    [self setupMap];

    return YES;
}

#pragma mark - set up IQKeyboardManager
- (void)setupKeyboardManager {
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
}

#pragma mark - setup map
- (void)setupMap {
    [AMapServices sharedServices].apiKey = AMAP_API_KEY;
}

#pragma mark - navigationbar style
- (void)setNavigationBarStyle {
    // hide 1px bottom line of navigationbar
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init]
                                      forBarPosition:UIBarPositionAny
                                          barMetrics:UIBarMetricsDefault];
    
    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:BUTTON_ACTIVE_COLOR];
    
    // hide back title
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
}

#pragma mark - set up main viewController
- (void)setupMainViewController {
    GMDebtorListViewController *clientViewController = [[GMDebtorListViewController alloc] init];
    GMMenuViewController *menuViewController = [[GMMenuViewController alloc] init];

    GMNavigationController *centerNavigationVC = [[GMNavigationController alloc] initWithRootViewController:clientViewController];
    GMNavigationController *leftNavigationVC = [[GMNavigationController alloc] initWithRootViewController:menuViewController];

    self.drawerController = [[MMDrawerController alloc] initWithCenterViewController:centerNavigationVC leftDrawerViewController:leftNavigationVC];
    self.drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    self.drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;

    self.drawerController.maximumLeftDrawerWidth = 200.0;

    self.window.rootViewController = self.drawerController;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
